import React, { useEffect, useState } from 'react'
import ProForm, { ProFormSelect, ProFormText } from '@ant-design/pro-form'
import { Form, Input, TreeSelect } from 'antd'
import { categoryList } from '@/services/category'
import Modal from 'antd/es/modal/Modal'
import ProFormItem from '@ant-design/pro-form/es/components/FormItem'

function UpdateForm (props) {
  /** 获取父类数据 **/
  const { updateModalVisit, setUpdateModalVisit, group, treeData, categoryDetail, updateCategory, categoryLists } = props
  /** 获取分组信息数据 **/
  const [children, setChildren] = useState([])

  useEffect(async () => {
    setChildren(treeData(categoryLists))
  }, [categoryLists, categoryDetail])

  /**
   * 更换树状图
   * @param value
   * @returns {Promise<void>}
   */
  const onSelected = async value => {
    /** 获取科目分组 **/
    const data = await categoryList({ category_group: value })
    setChildren(treeData(data))
  }

  return (
    categoryDetail === undefined ? '' :
      <Modal
        preserve={false}
        title="修改分类"
        destroyOnClose={true}
        visible={updateModalVisit}
        onCancel={setUpdateModalVisit}
        layout={'inline'}
        size="small"
        width={520}
        footer={null}
      >
        <ProForm
          onFinish={values => updateCategory(values)}
        >
          <Form.Item hidden name="id" initialValue={categoryDetail.id}>
            <Input/>
          </Form.Item>
          <ProFormSelect
            label="选择分组"
            name="category_group"
            initialValue={props.initialValue}
            valueEnum={group}
            fieldProps={{ onSelect: (e) => onSelected(e) }}
            rules={[
              { required: true, message: '请选择分组' },
            ]}
          />
          <ProFormItem
            label="选择父级"
            name="pid"
            initialValue={categoryDetail.pid}
            rules={[
              { required: true, message: '请选择分类' },
            ]}
          >
            <TreeSelect
              treeDefaultExpandAll
              placeholder="选择分类"
              treeData={children}
            />
          </ProFormItem>
          <ProFormText
            label="分类名称"
            placeholder="请输入2位到24位的名称"
            name="name"
            initialValue={categoryDetail.name}
            rules={[
              { required: true, message: '请填写分类名称' },
              { min: 2, message: '分类名称最少需要2位' },
              { max: 24, message: '分类名称最多只能24位' },
            ]}
          >
            <Input/>
          </ProFormText>
        </ProForm>
      </Modal>
  )
}

export default UpdateForm
